package net.JwtDemo.PasswordEncoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.Objects;

@Slf4j
public class Md5PasswordEncoder implements PasswordEncoder {	
	
	public static String bytesToHex(byte[] bytes) {
		StringBuilder result = new StringBuilder();
		for (byte b : bytes) {
			result.append(String.format("%02x", b));
		}
		return result.toString();
	}
	
	@Override
	public String encode(CharSequence rawPassword) {
		//public static String encrypt2ToMD5(String str) {
		String passwd = rawPassword.toString();
		String hexStr = "";
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] digest = md5.digest(passwd.getBytes("utf-8"));
			hexStr = bytesToHex(digest);
		} catch (Exception e) {
			throw new RuntimeException("MD5加密失败，"+e.getMessage());
		}
		return hexStr;			
	}

	@Override
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		log.info("rawPassword="+rawPassword+",encodePassword="+encodedPassword);
		String passwd = encode(rawPassword);
		log.info("rawPassword.encode="+passwd);
		return Objects.equals(encodedPassword, passwd);
	}
	

}
